﻿using System;
using System.Collections.Generic;
using GeoAPI.Geometries;
using NetTopologySuite.Geometries;

namespace NetTopologySuite.Simplify
{
	public class TaggedLineString
	{
		public TaggedLineString(ILineString parentLine) : this(parentLine, 2)
		{
		}

		public TaggedLineString(ILineString parentLine, int minimumSize)
		{
			this._parentLine = parentLine;
			this._minimumSize = minimumSize;
			this.Init();
		}

		public int MinimumSize
		{
			get
			{
				return this._minimumSize;
			}
		}

		public ILineString Parent
		{
			get
			{
				return this._parentLine;
			}
		}

		public Coordinate[] ParentCoordinates
		{
			get
			{
				return this._parentLine.Coordinates;
			}
		}

		public Coordinate[] ResultCoordinates
		{
			get
			{
				return TaggedLineString.ExtractCoordinates(this._resultSegs);
			}
		}

		public int ResultSize
		{
			get
			{
				int count = this._resultSegs.Count;
				if (count != 0)
				{
					return count + 1;
				}
				return 0;
			}
		}

		public TaggedLineSegment GetSegment(int i)
		{
			return this._segs[i];
		}

		private void Init()
		{
			Coordinate[] coordinates = this._parentLine.Coordinates;
			this._segs = new TaggedLineSegment[coordinates.Length - 1];
			for (int i = 0; i < coordinates.Length - 1; i++)
			{
				TaggedLineSegment taggedLineSegment = new TaggedLineSegment(coordinates[i], coordinates[i + 1], this._parentLine, i);
				this._segs[i] = taggedLineSegment;
			}
		}

		public TaggedLineSegment[] Segments
		{
			get
			{
				return this._segs;
			}
		}

		public void AddToResult(LineSegment seg)
		{
			this._resultSegs.Add(seg);
		}

		public ILineString AsLineString()
		{
			Coordinate[] coordinates = TaggedLineString.ExtractCoordinates(this._resultSegs);
			return this._parentLine.Factory.CreateLineString(coordinates);
		}

		public ILinearRing AsLinearRing()
		{
			Coordinate[] coordinates = TaggedLineString.ExtractCoordinates(this._resultSegs);
			return this._parentLine.Factory.CreateLinearRing(coordinates);
		}

		private static Coordinate[] ExtractCoordinates(IList<LineSegment> segs)
		{
			Coordinate[] array = new Coordinate[segs.Count + 1];
			LineSegment lineSegment = null;
			for (int i = 0; i < segs.Count; i++)
			{
				lineSegment = segs[i];
				array[i] = lineSegment.P0;
			}
			if (lineSegment != null)
			{
				array[array.Length - 1] = lineSegment.P1;
			}
			return array;
		}

		private readonly ILineString _parentLine;

		private TaggedLineSegment[] _segs;

		private readonly IList<LineSegment> _resultSegs = new List<LineSegment>();

		private readonly int _minimumSize;
	}
}
